package weixin.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConvertUtil {
	private static Logger logger = LoggerFactory.getLogger(ConvertUtil.class);

	public static Map<String, String> getMessagePropertyMap(InputStream in) {
		Map<String, String> propertyMap = new HashMap<String, String>();
		SAXBuilder builder = new SAXBuilder();
		Document doc = null;
		try {
			doc = builder.build(in);
		} catch (JDOMException e1) {
			e1.printStackTrace();
			logger.error("parse message body error!");
		} catch (IOException e1) {
			e1.printStackTrace();
			logger.error("parse message body error!");
		}
		if (doc != null) {
			Element root = doc.getRootElement();
			if (root != null) {
				List<Element> children = root.getChildren();
				Iterator<Element> cit = children.iterator();
				while (cit.hasNext()) {
					Element e = cit.next();
					propertyMap.put(e.getName(), e.getText());
				}
			}
		}
		return propertyMap;
	}

	public static void main(String[] args) throws JDOMException, IOException {
		String msg = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId></xml>";
		Map<String, String> xml2Map = ConvertUtil
				.getMessagePropertyMap(new ByteArrayInputStream(msg.getBytes()));
		Iterator<Entry<String, String>> it = xml2Map.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			System.out.println("entry is: " + entry.getKey() + ",value is: "
					+ entry.getValue());
		}
	}
}
